package com.fengba.nanzhi.tabbar03;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.notice.Notice;
import com.fengba.nanzhi.tabbar04.Tabbar04Item;
import com.fengba.nanzhi.tabbar04.Tabbar04ItemAdpter;
import com.fengba.nanzhi.tabbar04.wz.AddressActivity;
import com.fengba.nanzhi.tabbar04.wz.ParentUserActivity;
import com.fengba.nanzhi.tabbar04.wz.WebViewActivity;
import com.fengba.nanzhi.utils.DDImageTxtFragment;
import com.fengba.nanzhi.utils.Function;
import com.fengba.nanzhi.utils.OKManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by duan on 2018/4/1.
 */

public class Tabbar03 extends Fragment {
    private View self_view;
    private ListView self_listview;
    private OKManager manager = OKManager.getInstance();
    private JSONArray data3Arr;
    //List头部
    View headView = null;
    //刷新控件
    private SmartRefreshLayout refresh;

    public static Tabbar03 newInstance(String param){
        Tabbar03 tabbar03 = new Tabbar03();
        Bundle args = new Bundle();
        args.putString("agrs3",param);
        tabbar03.setArguments(args);
        return tabbar03;
    }

    public Tabbar03(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){

        if(self_view !=null){
            return self_view;
        }

        initData();

        /**
         * 本类中layout的View
         */
        View view = inflater.inflate(R.layout.tabbar03,container,false);
        self_view = view;

        /**
         * 屏幕的宽高
         */
        int screenWidth = Function.getScreenWidth(this.getActivity());
        int screenHeight = Function.getScreenHeight(this.getActivity());
        int screenWidthDP = Function.getScreenWidthReturnDP(this.getActivity());
        int screenHeightDP = Function.getScreenHeightReturnDP(this.getActivity());

        /**
         * 状态栏
         */
        View status_view = view.findViewById(R.id.view_statusbar);
        RelativeLayout.LayoutParams status_view_params = new RelativeLayout.LayoutParams(0,0);
        status_view_params.width = screenWidth;
        status_view_params.height = Function.getStatusBarHeight(this.getActivity());
        status_view.setLayoutParams(status_view_params);

        /**
         * tabbar列表
         */
        self_listview = (ListView)view.findViewById(R.id.self_list_view);
        headView = inflater.inflate(R.layout.tabbar03_list_header,null);
        Tabbar03ItemAdpter itemAdpter = new Tabbar03ItemAdpter(getActivity(),null);
        self_listview.addHeaderView(headView);
        self_listview.setAdapter(itemAdpter);
        self_listview.setOnItemClickListener(mItemClickListener);


        /**
         * 刷新控件
         */
        refresh = (SmartRefreshLayout)view.findViewById(R.id.refresh);

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        //结束加载
                        //refresh.finishRefresh();
                        initData();
                        //Log.e("x","xx");
                        //加载失败的话3秒后结束加载
                        //refreshlayout.finishRefresh(3000);
                    }
                },0);
            }
        });


        return view;
    }


    /**
     * 初始化数据
     */
    private void initData() {
        OKManager.getInstance().type0002(new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                //Log.e("xxx",jsonObject.toString());
                refresh.finishRefresh();
                try {
                    //左上角第一张
                    JSONArray data1Arr = (JSONArray)jsonObject.get("data1");
                    JSONObject data1Object = (JSONObject) data1Arr.getJSONObject(0);
                    //左上角第一张
                    JSONArray data2Arr = (JSONArray)jsonObject.get("data2");
                    //list数据
                    data3Arr = (JSONArray)jsonObject.get("data3");

                    //headView
                    final ImageView img01 = headView.findViewById(R.id.image01);
                    final ImageView img02 = headView.findViewById(R.id.image02);
                    final ImageView img03 = headView.findViewById(R.id.image03);
                    final TextView txt01 = headView.findViewById(R.id.txt01);
                    TextView txt02 = headView.findViewById(R.id.txt02);
                    TextView txt03 = headView.findViewById(R.id.txt03);
                    //获取good数据
                    JSONObject good1 = (JSONObject) data1Object.get("goods");
                    JSONObject good2 = (JSONObject) data2Arr.getJSONObject(0);
                    JSONObject good3 = (JSONObject) data2Arr.getJSONObject(1);
                    //获取good的图片
                    String firstPic = good1.get("images").toString().split(",")[0];
                    String secondPic = good2.get("images").toString().split(",")[0];
                    String thirdPic = good3.get("images").toString().split(",")[0];
                    //图片下载
                    OKManager.getInstance().asyncBitmapByUrl(firstPic, new OKManager.func3() {
                        @Override
                        public void onResponse(Bitmap bitmap) {
                            img01.setImageBitmap(bitmap);
                        }
                    });
                    OKManager.getInstance().asyncBitmapByUrl(secondPic, new OKManager.func3() {
                        @Override
                        public void onResponse(Bitmap bitmap) {
                            img02.setImageBitmap(bitmap);
                        }
                    });
                    OKManager.getInstance().asyncBitmapByUrl(thirdPic, new OKManager.func3() {
                        @Override
                        public void onResponse(Bitmap bitmap) {
                            img03.setImageBitmap(bitmap);
                        }
                    });
                    //时间
                    Date date = new Date();
                    long starttime = date.getTime();
                    String endtime = data1Object.get("endtime").toString();
                    final long time = Function.string2Time(endtime)-starttime;
                    txt02.setText(Function.phoneHide4Start(good2.get("mobile").toString()));
                    txt03.setText(Function.phoneHide4Start(good3.get("mobile").toString()));
                    new CountDownTimer(time,1000){
                        /**
                         * 固定间隔被调用,就是每隔countDownInterval会回调一次方法onTick
                         * @param millisUntilFinished
                         */
                        @Override
                        public void onTick(long millisUntilFinished) {
                            txt01.setText(formatTime(millisUntilFinished));
                        }

                        /**
                         * 倒计时完成时被调用
                         */
                        @Override
                        public void onFinish() {
                            txt01.setText("00:00:00");
                        }
                    }.start();

                    //List数据
                    Tabbar03ItemAdpter itemAdpter = new Tabbar03ItemAdpter(getActivity(),data3Arr);
                    self_listview.setAdapter(itemAdpter);
                }catch (JSONException e){
                    refresh.finishRefresh();
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                //Log.e("xxx",string);
            }
        });
    }

    /**
     * 将毫秒转化为 分钟：秒 的格式
     *
     * @param millisecond 毫秒
     * @return
     */
    public String formatTime(long millisecond) {
        int hour;//小时
        int minute;//分钟
        int second;//秒数
        hour   = (int) ((millisecond / 1000) / 60 / 60 );
        minute = (int) ((millisecond / 1000) / 60 % 60);
        second = (int) ((millisecond / 1000) % 60);
        if (minute < 10) {
            if (second < 10) {
                return hour+":"+"0" + minute + ":" + "0" + second;
            } else {
                return hour+":"+"0" + minute + ":" + second;
            }
        }else {
            if (second < 10) {
                return hour+":"+minute + ":" + "0" + second;
            } else {
                return hour+":"+minute + ":" + second;
            }
        }
    }

    AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2,
                                long arg3) {
            //Log.e("xxx","你好");
            /**
             * 延时点击
             */
            arg1.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_cell_gray));
            new Handler().postDelayed(new Runnable(){
                public void run() {
                    arg1.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_white));
                }
            }, 10);

            try {
                JSONObject good = (JSONObject) data3Arr.getJSONObject(arg2-1);
                Intent intent = new Intent(getActivity(), GoodInfo.class);
                intent.putExtra("good", good.toString());
                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    };

}
